/******************************************************************************************************
Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals FileDialog, settings, Dir, File, serialization, TextStream, ProgressDialog, MessageBox, qsTr, Application, print, DBPlugin, MnUi*/
/*jslint plusplus: true, indent: 4*/

function dbPlayMNSRFile() {
	"use strict";
	var s, inFile, progress, numRequests, inStream, line, startTime, requestCount, buffer, ok, request, l, response,
	// Settings keys
		inFileSettingsKey = "Play MNSR File/Last File",
	// Prompt for file to import
		inFileName = FileDialog.getOpenFileName("MNSR Files (*.mnsr)", "Select File", settings.value(inFileSettingsKey, Dir.home()));

	if (!inFileName) {
		return;
	}
	settings.setValue(inFileSettingsKey, inFileName);

	// Check that file is readable
	s = serialization;
	s.fileHistory = false;
	inFile = new File(inFileName);
	if (!inFile.open(File.ReadOnly)) {
		MessageBox.critical(qsTr("Could not open file '{0}'.").format(inFileName));
		return;
	}

	progress = new ProgressDialog();
	// First run: count requests
	progress.setRange(0, 2);
	progress.value = 1;
	progress.labelText = qsTr("Reading file...");
	progress.show();
	Application.mainWindow.setBusy(qsTr("Counting requests..."));
	numRequests = 0;
	inStream = new TextStream(inFile);
	while (!inStream.atEnd()) {
		line = inStream.readLine();
		print("'" + line + "'");
		if (line === String.fromCharCode(4)) {
			numRequests++;
			//mainWindow.setStatusMessage("Counting requests: " + numRequests + "...");
			progress.labelText = qsTr("Counting requests: {0}...").format(numRequests);
		}
	}
	inFile.close();
	progress.close();
	Application.mainWindow.endBusy();

	// Check that file actually contains data
	if (numRequests === 0) {
		MessageBox.critical(qsTr("The file '{0}' does not contain any requests.").format(inFileName));
		return;
	}

	// Connect to server
	Application.mainWindow.doAction("dbConnect");
	if (!DBPlugin.client.connected()) {
		return;
	}

	// Last chance to bail out
	if (MessageBox.question(qsTr("Send {0} requests to the server?").format(numRequests), MessageBox.Yes, MessageBox.No) !== MessageBox.Yes) {
		return;
	}

	// Process file
	startTime = new Date();
	inFile = new File(inFileName);
	if (!inFile.open(File.ReadOnly)) {
		MessageBox.critical(qsTr("Could not open file '{0}'.".format(inFileName)));
		return;
	}
	inStream = new TextStream(inFile);

	requestCount = 0;
	buffer = [];
	ok = true;
	Application.mainWindow.setBusy(qsTr("Sending requests..."));
	progress = new ProgressDialog();
	progress.setRange(0, numRequests);
	progress.value = 0;
	progress.show();

	while (!(inStream.atEnd() || progress.wasCanceled) && ok) {
		line = inStream.readLine();
		//print("'" + line + "'");
		if (line === String.fromCharCode(4)) {
			requestCount++;
			//mainWindow.setStatusMessage("Sending request " + requestCount + " (" + buffer[1] + ") ...");
			progress.value = requestCount;
			progress.labelText = qsTr("Sending request {0} of {1}...").format(requestCount, numRequests);
			Application.mainWindow.processEvents();
			request = "";
			for (l = 0; l < buffer.length; l++) {
				request += buffer[l] + "\n";
			}
			request += line + "\n";
			response = DBPlugin.client.sendRequest(request);
			if (response.indexOf("ACCEPTED") !== 0) {
				Application.mainWindow.endBusy();
				MessageBox.critical(qsTr("Error while processing request {0} ({1}).\nThe server said:\n{2}").format(requestCount, buffer[1], response));
				ok = (MessageBox.question(qsTr("Continue sending requests?"), MessageBox.Yes, MessageBox.No) === MessageBox.Yes);
				Application.mainWindow.setBusy(qsTr("Sending requests..."));
			}
			buffer = [];
		} else {
			buffer.push(line);
		}
	}
	inFile.close();
	progress.close();
	Application.mainWindow.endBusy();
	if (ok) {
		MessageBox.information(qsTr("Successfully sent {0} requests.").format(numRequests));
	}
	print("All done in " + ((new Date() - startTime) / 1000) + " seconds.");
}

if (this.MnUi && MnUi.scripts_db) {
	MnUi.scripts_db.scripts_db_PlayMNSRFile = dbPlayMNSRFile;
}
